<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Zookeeper简介与环境搭建 | 王开琦的个人小站</title><meta name="keywords" content="分布式锁,统一命名服务,配置管理,集群管理,队列管理"><meta name="author" content="王开琦"><meta name="copyright" content="王开琦"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Zookeeper是一个分布式协调服务的开源框架，为分布式程序提供协调服务，同时用来解决分布式集群中应用系统的数据一致性问题。">
<meta property="og:type" content="article">
<meta property="og:title" content="Zookeeper简介与环境搭建">
<meta property="og:url" content="https://blog.wkq.pub/blog/18-%E5%88%86%E5%B8%83%E5%BC%8F%E6%9E%B6%E6%9E%84-%E5%88%86%E5%B8%83%E5%BC%8F%E5%8D%8F%E8%B0%83-Zookeeper%E7%AE%80%E4%BB%8B%E4%B8%8E%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA/index.html">
<meta property="og:site_name" content="王开琦的个人小站">
<meta property="og:description" content="Zookeeper是一个分布式协调服务的开源框架，为分布式程序提供协调服务，同时用来解决分布式集群中应用系统的数据一致性问题。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://blog.wkq.pub/cover/Zookeeper.jpg">
<meta property="article:published_time" content="2022-02-06T05:26:44.000Z">
<meta property="article:modified_time" content="2022-02-06T05:26:44.000Z">
<meta property="article:author" content="王开琦">
<meta property="article:tag" content="分布式锁">
<meta property="article:tag" content="统一命名服务">
<meta property="article:tag" content="配置管理">
<meta property="article:tag" content="集群管理">
<meta property="article:tag" content="队列管理">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://blog.wkq.pub/cover/Zookeeper.jpg"><link rel="shortcut icon" href="/media/favicon.ico"><link rel="canonical" href="https://blog.wkq.pub/blog/18-%E5%88%86%E5%B8%83%E5%BC%8F%E6%9E%B6%E6%9E%84-%E5%88%86%E5%B8%83%E5%BC%8F%E5%8D%8F%E8%B0%83-Zookeeper%E7%AE%80%E4%BB%8B%E4%B8%8E%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Zookeeper简介与环境搭建',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-02-06 13:26:44'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    document.addEventListener('pjax:complete', detectApple)})(window)</script><meta name="generator" content="Hexo 5.2.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="/media/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">15</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">17</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">15</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/media/top_img3.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">王开琦的个人小站</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Zookeeper简介与环境搭建</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-02-06T05:26:44.000Z" title="发表于 2022-02-06 13:26:44">2022-02-06</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-02-06T05:26:44.000Z" title="更新于 2022-02-06 13:26:44">2022-02-06</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E5%88%86%E5%B8%83%E5%BC%8F%E6%9E%B6%E6%9E%84/">分布式架构</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E5%88%86%E5%B8%83%E5%BC%8F%E6%9E%B6%E6%9E%84/%E5%88%86%E5%B8%83%E5%BC%8F%E5%8D%8F%E8%B0%83/">分布式协调</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">1.7k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>6分钟</span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><div class="note info simple"><p>ZK是用来做集群的分布式协调的，比如Kafka集群。</p>
</div>
<ul>
<li>做集群之间数据一致性的保障，比如节点宕机，故障转移等等。比如HDFS、Hadoop、等中间件都会依赖于ZK</li>
<li><code>Dubbo</code>也依赖于<code>Zookeeper</code></li>
</ul>
<hr>
<h2 id="Zookeeper基础知识、体系结构、系统模型"><a href="#Zookeeper基础知识、体系结构、系统模型" class="headerlink" title="Zookeeper基础知识、体系结构、系统模型"></a>Zookeeper基础知识、体系结构、系统模型</h2><ul>
<li>Zookeeper是一个类似linux、hdfs的树形文件结构，zookeeper可以用来保证数据在（Zookeeper）集群之间的数据的事务性、一致性，zookeeper也是我们常说的CAP理论中的CP（强一致性）；</li>
<li>Zookeeper有一个概念叫watch（也称之为事件），是一次性触发的的，当watch监视的数据发生变化时，通知设置了该watch的client端，即watcher实例对象（用于改变节点变化而做出相应的行为）</li>
</ul>
<hr>
<h2 id="Zookeeper有三个角色，Leader、Follower、Observer"><a href="#Zookeeper有三个角色，Leader、Follower、Observer" class="headerlink" title="Zookeeper有三个角色，Leader、Follower、Observer"></a>Zookeeper有三个角色，Leader、Follower、Observer</h2><ul>
<li><p>Leader：数据总控节点，用于接收客户端连接请求，分发给所有的Follower节点后，各个Follower节点进行更新数据操作并返回给leader节点，如果满足半数以上（所以Zookeeper集群一般是奇数个节点）更新成功则此次操作成功；</p>
</li>
<li><p>Follower：相当于跟随者的角色，Zookeeper的Leader宕机（挂掉）时，所有的Follower角色内部会产生选举机制，选举出新的Leader用于总控。</p>
</li>
<li><p>Observer：顾名思义，就是我们的客户端，用于观察Zookeeper集群的数据发送变化，如果产生变化则zookeeper会主动推送watch事件给Observer（客户端），用于对数据变化的后续处理；当然Observer（客户端）也可以发送数据变更请求；</p>
</li>
</ul>
<hr>
<h2 id="Zookeeper应用场景"><a href="#Zookeeper应用场景" class="headerlink" title="Zookeeper应用场景"></a>Zookeeper应用场景</h2><ul>
<li>统一命名服务（Name Service）</li>
<li>配置管理（Configuration Management）</li>
<li>集群管理（Group Membership）</li>
<li>共享锁（Locks）</li>
<li>队列管理</li>
</ul>
<hr>
<h2 id="Zookeeper集群环境搭建与配置："><a href="#Zookeeper集群环境搭建与配置：" class="headerlink" title="Zookeeper集群环境搭建与配置："></a>Zookeeper集群环境搭建与配置：</h2><figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line">1. 准备工作：</span><br><span class="line">## 准备3个节点，要求配置好主机名称，服务器之间系统时间保持一致</span><br><span class="line">## 注意 /etc/hostname 和 /etc/hosts 配置主机名称（在这个里我准备zk1,zk2,zk3三节点）</span><br><span class="line">## 特别注意 以下操作3个节点要同时进行操作哦！</span><br><span class="line">## 1.启动防火墙 systemctl start firewalld</span><br><span class="line">## 2.关闭防火墙 systemctl stop firewalld</span><br><span class="line">## 3.重启防火墙 systemctl restart firewalld</span><br><span class="line">## 4.查看防火墙 systemctl status firewalld</span><br><span class="line">## 5.开机禁用防火墙 systemctl disable firewalld</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">2. 上传zk到三台服务器节点</span><br><span class="line">## 注意我这里解压到/usr/local下</span><br><span class="line">2.1 进行解压： tar zookeeper-3.4.6.tar.gz</span><br><span class="line">2.2 重命名： mv zookeeper-3.4.6 zookeeper</span><br><span class="line">2.3 修改环境变量： vim /etc/profile </span><br><span class="line">## 这里要添加zookeeper的全局变量</span><br><span class="line">export ZOOKEEPER_HOME=/usr/local/zookeeper</span><br><span class="line">export PATH=.:$ZOOKEEPER_HOME/bin</span><br><span class="line">2.4 刷新环境变量： source /etc/profile</span><br><span class="line">2.5 到zookeeper下修改配置文件： </span><br><span class="line">2.5.1 首先到指定目录： cd /usr/local/zookeeper/conf</span><br><span class="line">2.5.2 然后复制zoo_sample.cfg文件，复制后为zoo.cfg： mv zoo_sample.cfg zoo.cfg</span><br><span class="line">2.5.3 然后修改两处地方, 最后保存退出：</span><br><span class="line">(1) 修改数据的dir</span><br><span class="line">dataDir=/usr/local/zookeeper/data</span><br><span class="line">(2) 修改集群地址</span><br><span class="line">server.0=zk1:2888:3888</span><br><span class="line">server.1=zk2:2888:3888</span><br><span class="line">server.2=zk3:2888:3888</span><br><span class="line"></span><br><span class="line">2.6 增加服务器标识配置，需要2步骤，第一是创建文件夹和文件，第二是添加配置内容： </span><br><span class="line">(1) 创建文件夹： mkdir /usr/local/zookeeper/data</span><br><span class="line">(2) 创建文件myid 路径应该创建在/usr/local/zookeeper/data下面，如下：</span><br><span class="line">	vim /usr/local/zookeeper/data/myid</span><br><span class="line">	注意这里每一台服务器的myid文件内容不同，分别修改里面的值为0，1，2；与我们之前的zoo.cfg配置文	 件里：server.0，server.1，server.2 顺序相对应，然后保存退出；</span><br><span class="line"></span><br><span class="line">2.7 到此为止，Zookeeper集群环境大功告成！启动zookeeper命令</span><br><span class="line">	启动路径：/usr/local/zookeeper/bin（也可在任意目录，因为配置了环境变量）</span><br><span class="line">	执行命令：zkServer.sh start (注意这里3台机器都要进行启动，启动之后可以查看状态)</span><br><span class="line">	查看状态：zkServer.sh status (在三个节点上检验zk的mode, 会看到一个leader和俩个follower)</span><br></pre></td></tr></table></figure>
<hr>
<h2 id="Zookeeper客户端操作"><a href="#Zookeeper客户端操作" class="headerlink" title="Zookeeper客户端操作"></a>Zookeeper客户端操作</h2><figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">zkCli.sh 进入zookeeper客户端</span><br><span class="line">根据提示命令进行操作： </span><br><span class="line">查找：ls /   ls /zookeeper</span><br><span class="line">创建并赋值： create /imooc zookeeper</span><br><span class="line">获取： get /imooc </span><br><span class="line">设值： set /imooc zookeeper1314 </span><br><span class="line">PS1: 任意节点都可以看到zookeeper集群的数据一致性</span><br><span class="line">PS2: 创建节点有俩种类型：短暂（ephemeral） 持久（persistent）, 这些小伙伴们可以查找相关资料，我们这里作为入门不做过多赘述！</span><br></pre></td></tr></table></figure>
<hr>
<h2 id="Zookeeper核心配置讲解：（zoo-cfg配置文件，扩展内容）"><a href="#Zookeeper核心配置讲解：（zoo-cfg配置文件，扩展内容）" class="headerlink" title="Zookeeper核心配置讲解：（zoo.cfg配置文件，扩展内容）"></a>Zookeeper核心配置讲解：（zoo.cfg配置文件，扩展内容）</h2><figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">（1）tickTime：基本事件单元，以毫秒为单位。这个时间是作为 Zookeeper 服务器之间或客户端与服务器之间维持心跳的时间间隔，也就是每隔 tickTime时间就会发送一个心跳。</span><br><span class="line">				</span><br><span class="line">（2）initLimit：这个配置项是用来配置 Zookeeper 接受客户端初始化连接时最长能忍受多少个心跳时间间隔数，当已经超过 10 个心跳的时间（也就是 tickTime）长度后 Zookeeper 服务器还没有收到客户端的返回信息，那么表明这个客户端连接失败。总的时间长度就是 10*2000=20 秒。</span><br><span class="line">		</span><br><span class="line">（3）syncLimit：这个配置项标识 Leader 与 Follower 之间发送消息，请求和应答时间长度，最长不能超过多少个 tickTime 的时间长度，总的时间长度就是 5*2000=10 秒</span><br><span class="line">				</span><br><span class="line">（4）dataDir：存储内存中数据库快照的位置，顾名思义就是 Zookeeper 保存数据的目录，默认情况下，Zookeeper 将写数据的日志文件也保存在这个目录里。</span><br><span class="line">   </span><br><span class="line">（5）clientPort： 这个端口就是客户端连接 Zookeeper 服务器的端口，Zookeeper 会监听这个端口，接受客户端的访问请求。</span><br><span class="line"></span><br><span class="line">（6）至于最后的配置项：server.A = B:C:D: </span><br><span class="line">A表示这个是第几号服务器,</span><br><span class="line">B 是这个服务器的 ip 地址；</span><br><span class="line">C 表示的是这个服务器与集群中的 Leader 服务器交换信息的端口；</span><br><span class="line">D 表示的是万一集群中的 Leader 服务器挂了，需要一个端口来重新进行选举，选出一个新的 Leader</span><br></pre></td></tr></table></figure>
<hr>
<h2 id="开机启动"><a href="#开机启动" class="headerlink" title="开机启动"></a>开机启动</h2><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">cd /etc/rc.d/init.d/ # 服务启动的目录,Linux开机的时候会去扫init.d下面的脚本去执行</span><br><span class="line">touch zookeeper</span><br><span class="line">chmod 777 zookeeper</span><br><span class="line">vim zookeeper</span><br><span class="line"></span><br><span class="line"><span class="meta">#</span><span class="bash"> 开机启动zookeeper脚本</span></span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#</span><span class="bash">chkconfig:2345 20 90</span></span><br><span class="line"><span class="meta">#</span><span class="bash">description:zookeeper</span></span><br><span class="line"><span class="meta">#</span><span class="bash">processname:zookeeper</span></span><br><span class="line">export JAVA_HOME=/usr/java/jdk1.8.0_202</span><br><span class="line">export PATH=$JAVA_HOME/bin:$PATH</span><br><span class="line">case $1 in</span><br><span class="line">          start) /usr/local/zookeeper/bin/zkServer.sh start;;</span><br><span class="line">          stop) /usr/local/zookeeper/bin/zkServer.sh stop;;</span><br><span class="line">          status) /usr/local/zookeeper/bin/zkServer.sh status;;</span><br><span class="line">          restart) /usr/local/zookeeper/bin/zkServer.sh restart;;</span><br><span class="line">          *)  echo &quot;require start|stop|status|restart&quot;  ;;</span><br><span class="line">esac</span><br><span class="line"></span><br><span class="line">开机启动配置：chkconfig zookeeper on</span><br><span class="line">验证：</span><br><span class="line">chkconfig --add zookeeper</span><br><span class="line">chkconfig --list zookeeper</span><br><span class="line"></span><br><span class="line">这个时候我们就可以用servicezookeeper start/stop来启动停止zookeeper服务了</span><br><span class="line"></span><br><span class="line">使用chkconfig--add zookeeper命令把zookeeper添加到开机启动里面</span><br><span class="line"></span><br><span class="line">添加完成之后接这个使用chkconfig--list 来看看我们添加的zookeeper是否在里面</span><br><span class="line"></span><br><span class="line">如果上面的操作都正常的话；你就可以重启你的linux服务器了</span><br></pre></td></tr></table></figure>
</article><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/">分布式锁</a><a class="post-meta__tags" href="/tags/%E7%BB%9F%E4%B8%80%E5%91%BD%E5%90%8D%E6%9C%8D%E5%8A%A1/">统一命名服务</a><a class="post-meta__tags" href="/tags/%E9%85%8D%E7%BD%AE%E7%AE%A1%E7%90%86/">配置管理</a><a class="post-meta__tags" href="/tags/%E9%9B%86%E7%BE%A4%E7%AE%A1%E7%90%86/">集群管理</a><a class="post-meta__tags" href="/tags/%E9%98%9F%E5%88%97%E7%AE%A1%E7%90%86/">队列管理</a></div><div class="post_share"><div class="social-share" data-image="/cover/Zookeeper.jpg" data-sites="wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/blog/14-分布式架构-分布式锁-单体应用锁与分布式锁/" title="单体应用锁及分布式锁"><img class="cover" src= "" data-lazy-src="/cover/%E5%8D%95%E4%BD%93%E5%BA%94%E7%94%A8%E9%94%81%E5%8F%8A%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-01-10</div><div class="title">单体应用锁及分布式锁</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="/media/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">王开琦</div><div class="author-info__description">今日事今日毕</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">15</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">17</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">15</div></a></div></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Zookeeper%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86%E3%80%81%E4%BD%93%E7%B3%BB%E7%BB%93%E6%9E%84%E3%80%81%E7%B3%BB%E7%BB%9F%E6%A8%A1%E5%9E%8B"><span class="toc-number">1.</span> <span class="toc-text">Zookeeper基础知识、体系结构、系统模型</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Zookeeper%E6%9C%89%E4%B8%89%E4%B8%AA%E8%A7%92%E8%89%B2%EF%BC%8CLeader%E3%80%81Follower%E3%80%81Observer"><span class="toc-number">2.</span> <span class="toc-text">Zookeeper有三个角色，Leader、Follower、Observer</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Zookeeper%E5%BA%94%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="toc-number">3.</span> <span class="toc-text">Zookeeper应用场景</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Zookeeper%E9%9B%86%E7%BE%A4%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA%E4%B8%8E%E9%85%8D%E7%BD%AE%EF%BC%9A"><span class="toc-number">4.</span> <span class="toc-text">Zookeeper集群环境搭建与配置：</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Zookeeper%E5%AE%A2%E6%88%B7%E7%AB%AF%E6%93%8D%E4%BD%9C"><span class="toc-number">5.</span> <span class="toc-text">Zookeeper客户端操作</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Zookeeper%E6%A0%B8%E5%BF%83%E9%85%8D%E7%BD%AE%E8%AE%B2%E8%A7%A3%EF%BC%9A%EF%BC%88zoo-cfg%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%EF%BC%8C%E6%89%A9%E5%B1%95%E5%86%85%E5%AE%B9%EF%BC%89"><span class="toc-number">6.</span> <span class="toc-text">Zookeeper核心配置讲解：（zoo.cfg配置文件，扩展内容）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%BC%80%E6%9C%BA%E5%90%AF%E5%8A%A8"><span class="toc-number">7.</span> <span class="toc-text">开机启动</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blog/3-%E6%95%B0%E6%8D%AE%E5%BA%93-%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9B%91%E6%8E%A7%E4%B8%8E%E8%B0%83%E4%BC%98-%E7%89%B9%E5%AE%9A%E8%AF%AD%E5%8F%A5%E7%9A%84%E5%8E%9F%E7%90%86%E5%92%8C%E8%B0%83%E4%BC%98/" title="3.数据库-数据库监控与调优-特定语句的原理和调优"><img src= "" data-lazy-src="/media/top_img.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="3.数据库-数据库监控与调优-特定语句的原理和调优"/></a><div class="content"><a class="title" href="/blog/3-%E6%95%B0%E6%8D%AE%E5%BA%93-%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9B%91%E6%8E%A7%E4%B8%8E%E8%B0%83%E4%BC%98-%E7%89%B9%E5%AE%9A%E8%AF%AD%E5%8F%A5%E7%9A%84%E5%8E%9F%E7%90%86%E5%92%8C%E8%B0%83%E4%BC%98/" title="3.数据库-数据库监控与调优-特定语句的原理和调优">3.数据库-数据库监控与调优-特定语句的原理和调优</a><time datetime="2022-04-22T08:14:26.000Z" title="发表于 2022-04-22 16:14:26">2022-04-22</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/3-%E6%95%B0%E6%8D%AE%E5%BA%93-%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9B%91%E6%8E%A7%E4%B8%8E%E8%B0%83%E4%BC%98-%E6%95%B0%E6%8D%AE%E5%BA%93%E8%B0%83%E4%BC%98%E7%90%86%E8%AE%BA/" title="数据库调优理论"><img src= "" data-lazy-src="/media/top_img.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="数据库调优理论"/></a><div class="content"><a class="title" href="/blog/3-%E6%95%B0%E6%8D%AE%E5%BA%93-%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9B%91%E6%8E%A7%E4%B8%8E%E8%B0%83%E4%BC%98-%E6%95%B0%E6%8D%AE%E5%BA%93%E8%B0%83%E4%BC%98%E7%90%86%E8%AE%BA/" title="数据库调优理论">数据库调优理论</a><time datetime="2022-04-22T08:13:31.000Z" title="发表于 2022-04-22 16:13:31">2022-04-22</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/3-%E6%95%B0%E6%8D%AE%E5%BA%93-%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9B%91%E6%8E%A7%E4%B8%8E%E8%B0%83%E4%BC%98-%E6%85%A2%E6%9F%A5%E8%AF%A2%E5%8F%91%E7%8E%B0%E4%B8%8E%E5%88%86%E6%9E%90/" title="慢查询发现与分析"><img src= "" data-lazy-src="/media/top_img.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="慢查询发现与分析"/></a><div class="content"><a class="title" href="/blog/3-%E6%95%B0%E6%8D%AE%E5%BA%93-%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9B%91%E6%8E%A7%E4%B8%8E%E8%B0%83%E4%BC%98-%E6%85%A2%E6%9F%A5%E8%AF%A2%E5%8F%91%E7%8E%B0%E4%B8%8E%E5%88%86%E6%9E%90/" title="慢查询发现与分析">慢查询发现与分析</a><time datetime="2022-04-22T08:12:32.000Z" title="发表于 2022-04-22 16:12:32">2022-04-22</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/1-Java-JVM%E8%B0%83%E4%BC%98%E7%90%86%E8%AE%BA/" title="JVM 调优理论"><img src= "" data-lazy-src="/media/top_img.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JVM 调优理论"/></a><div class="content"><a class="title" href="/blog/1-Java-JVM%E8%B0%83%E4%BC%98%E7%90%86%E8%AE%BA/" title="JVM 调优理论">JVM 调优理论</a><time datetime="2022-04-21T06:40:41.000Z" title="发表于 2022-04-21 14:40:41">2022-04-21</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/20-%E5%BE%AE%E6%9C%8D%E5%8A%A1%E6%9E%B6%E6%9E%84-%E6%9C%8D%E5%8A%A1%E6%B2%BB%E7%90%86-%E6%9C%8D%E5%8A%A1%E6%B2%BB%E7%90%86Eureka/" title="服务治理Eureka"><img src= "" data-lazy-src="/media/top_img.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="服务治理Eureka"/></a><div class="content"><a class="title" href="/blog/20-%E5%BE%AE%E6%9C%8D%E5%8A%A1%E6%9E%B6%E6%9E%84-%E6%9C%8D%E5%8A%A1%E6%B2%BB%E7%90%86-%E6%9C%8D%E5%8A%A1%E6%B2%BB%E7%90%86Eureka/" title="服务治理Eureka">服务治理Eureka</a><time datetime="2022-04-13T13:18:27.000Z" title="发表于 2022-04-13 21:18:27">2022-04-13</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="footer_custom_text">Copyright© 2022 blog.wkq.pub <span>陇ICP备2021003596号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      true && mermaid.init()
    })
  }
}</script></div><div class="aplayer no-destroy" data-id="7675104902" data-server="tencent" data-type="playlist" data-fixed="true" data-mini="true" data-listFolded="false" data-order="random" data-preload="none" data-autoplay="true" muted></div><canvas class="fireworks" mobile="true"></canvas><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/fireworks.min.js"></script><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/gh/metowolf/MetingJS@1.2/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = [
  'title',
  '#config-diff',
  '#body-wrap',
  '#rightside-config-hide',
  '#rightside-config-show',
  '.js-pjax'
]

if (false) {
  pjaxSelectors.unshift('meta[property="og:image"]', 'meta[property="og:title"]', 'meta[property="og:url"]')
}

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.removeEventListener('scroll', window.tocScrollFn)
  window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // Analytics
  if (false) {
    MtaH5.pgv()
  }

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script></div><script src="/live2d_models/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2d_models/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"jsonPath":"/live2d_models/assets/penchan.model.json"},"display":{"position":"left","width":100,"height":150,"hOffset":-10,"vOffset":40},"mobile":{"show":true},"react":{"opacity":0.7},"log":false});</script></body></html>